
import 'dart:io';

import 'package:eyepetizer_example/http/Url.dart';
import 'package:eyepetizer_example/widget/go_navigation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../config/string.dart';

class WebPage extends StatefulWidget {

  final String url;
  const WebPage({Key? key, required this.url}) : super(key: key);

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  WebViewController? _controller;
  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      body: WillPopScope(
        onWillPop: _onWillPop,
        child: Container(
          alignment: Alignment.center,
          child: _initWebView(),
        ),
      ),
    );
  }

  Widget _initWebView() {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: WebView(
        initialUrl: widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController controller){
          _controller = controller;
          // 根据元素的 class 属性值查询一组元素节点对象
          _controller?.runJavascript(JS.js);
        },
      ),
    );
  }

  AppBar _appBar() {
    return AppBar(
      // 导航栏最左侧 Widget，返回箭头
      leading: GestureDetector(
        onTap: () {
          _controller?.canGoBack().then((canBack) {
            if(canBack) {
              _controller?.goBack();
            }else {
              GoNavigator.back(context);
            }
          });
        },
        child: const Icon(
          Icons.arrow_back,
          size: 25,
          color: Colors.black,
        ),
      ),
      // title文本：新鲜资讯
      title: const Text(
        AppString.news_title,
        style: TextStyle(
            color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      backgroundColor: Colors.white,
      elevation: 0.0,
      systemOverlayStyle: SystemUiOverlayStyle.light,
    );
  }

  Future<bool> _onWillPop()  {
    var backFuture = _controller?.canGoBack().then((canBack) {
      if(canBack) {
        _controller?.goBack();
          return Future.value(false);
      }else {
          return Future.value(true);
      }
    });

    if(backFuture == null) {
      return Future.value(true);
    }

    return backFuture;
  }
}
